var can = document.querySelector('#myCanvas'), 
    score = document.querySelector('#score'), 
    second = document.querySelector('#second'), 
    ctx = can.getContext('2d'), 
    t, timer, s = 0, size = 20;

function Rect(x, y, w, h, c, b){
	this.x = x, this.y = y, this.w = w, this.h = h, this.c = c, this.b = b;
}

Rect.prototype.draw = function(){
  //ctx.fillStyle = color ; ctx.fillStyle = gradient 渐变对象
  ctx.fillStyle = this.c, ctx.strokeStyle = this.b, ctx.lineWidth = 2;

  ctx.beginPath();
  ctx.arc(this.x + size / 2, this.y + size / 2, size / 2, 0, 2 * Math.PI, false);
  ctx.fill();

  ctx.beginPath();
  ctx.arc(this.x + size / 2, this.y + size / 2, size / 2, 0, 2 * Math.PI, false);
  ctx.stroke();
}

function Snake(){
	this.rectsArr = [], this.rectSize = this.rectsArr.length || 3, this.dir = 'DOWN', this.speed = 200;

	for(var i = 0; i < this.rectSize; i++){
    this.rectsArr.push(
      new Rect(0, i * size, size, size, (i === this.rectSize - 1 ? 'red' : 'lime'), '#000')
    );
	}
}

Snake.prototype.move = function(){
	var head = this.rectsArr[this.rectsArr.length - 1], that = this;

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  creatFood(this.rectsArr);
  
  timer = setInterval(function(){
    s++;
    second.innerHTML = s;
  }, 1000);

	t = setInterval(function(){
    
		for(var i in that.rectsArr){
			ctx.clearRect(that.rectsArr[i].x, that.rectsArr[i].y, size, size);

			if(i != that.rectsArr.length - 1){
				that.rectsArr[i].x = that.rectsArr[Number(i) + 1].x;
				that.rectsArr[i].y = that.rectsArr[Number(i) + 1].y;
			}
    }

    if(that.dir === 'DOWN'){
      head.y = head.y == ctx.canvas.height ? 0 : (head.y + size);
    }else if(that.dir === 'UP'){
      head.y = head.y == -size ? (ctx.canvas.height - size) : (head.y - size);
    }else if(that.dir === 'RIGHT'){
      head.x = head.x == ctx.canvas.width + size ? 0 : (head.x + size);
    }else if(that.dir === 'LEFT'){
      head.x = head.x == -size ? (ctx.canvas.width - size) : (head.x - size);
    }

    for(var i = 0; i < that.rectsArr.length; i++){
      that.rectsArr[i].draw();

      if(i != that.rectsArr.length - 1){
      	if(head.x === that.rectsArr[i].x && head.y === that.rectsArr[i].y){
          s = 0;
          clearInterval(t);
          clearInterval(timer);
      		ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
          document.querySelectorAll('button')[0].disabled = '';
          alert('GAME OVER');
          snake = new Snake();
      		return;
      	}
      }
  	}
    
    if(snake.foodX === head.x && snake.foodY === head.y){
      creatFood(that.rectsArr);

      if(that.rectsArr[0].x === that.rectsArr[1].x){
        if(that.rectsArr[0].y > that.rectsArr[1].y){
          var x = that.rectsArr[0].x;
          var y = that.rectsArr[0].y + size;
        }else if(that.rectsArr[0].y < that.rectsArr[1].y){
          var x = that.rectsArr[0].x;
          var y = that.rectsArr[0].y - size;
        }
      }else if(that.rectsArr[0].y === that.rectsArr[1].y){
        if(that.rectsArr[0].x > that.rectsArr[1].x){
          var x = that.rectsArr[0].x + size;
          var y = that.rectsArr[0].y;
        }else if(that.rectsArr[0].x < that.rectsArr[1].x){
          var x = that.rectsArr[0].x - size;
          var y = that.rectsArr[0].y;
        }
      }

      that.rectsArr.unshift(new Rect(x, y, size, size, 'lime', '#000'));
      score.innerHTML = Number(score.innerText) + 1;
    }
	}, that.speed);
}

var snake = new Snake();

function startGame(obj){
  snake.move();
  obj.disabled = 'disabled';
}

function pauseGame(obj){
  clearInterval(t);
  clearInterval(timer);
  document.querySelectorAll('button')[0].disabled = '';
}

function resetGame(){
  s = 0;
  clearInterval(t);
  clearInterval(timer);
  document.querySelectorAll('button')[0].disabled = '';
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  score.innerHTML = '0';
  second.innerHTML = '0';
  snake = new Snake();
}

document.onkeydown = function(e){
	if((e || event).keyCode === 38){
		snake.dir = snake.dir !== 'DOWN' ? 'UP' : 'DOWN';
	}else if((e || event).keyCode === 40){
    snake.dir = snake.dir !== 'UP' ? 'DOWN' : 'UP';
  }else if((e || event).keyCode === 37){
  	snake.dir = snake.dir !== 'RIGHT' ? 'LEFT' : 'RIGHT';
  }else if((e || event).keyCode === 39){
  	snake.dir = snake.dir !== 'LEFT' ? 'RIGHT' : 'LEFT';
  }
}

function creatFood(rectsArr){
	snake.foodX = positions().x; 
	snake.foodY = positions().y;

	for(var i = 0; i < rectsArr.length; i++){
    if(snake.foodX === rectsArr[i].x && snake.foodY === rectsArr[i].y){
    	snake.foodX = positions().x; 
      snake.foodY = positions().y;
    }
	}

	new Rect(snake.foodX, snake.foodY, size, size, 'yellow', '#000').draw();
}

function positions(){
  var arr = [];

	for(var i = 0; i <= ctx.canvas.width - size; i++){
    if(i % size === 0){
      arr.push(i);
    }
	}

	return{
    x: arr[Math.floor(Math.random() * arr.length + 1) - 1],
    y: arr[Math.floor(Math.random() * arr.length + 1) - 1]
  }
}